package com.xxl.sso.server.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.xxl.sso.core.conf.Conf.ThethirdConstant;
import com.xxl.sso.core.data.SsSsoCacheData;
import com.xxl.sso.core.entity.thethird.ThirdWebsiteInfo;
import com.xxl.sso.core.login.SsoTokenLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.service.UserService;

/**
 * sso server (for web)
 *
 * @author xuxueli 2017-08-01 21:39:47
 */
@Controller
@RequestMapping("/ajax")
public class AjaxController {
    @Autowired
    private UserService userService;

    /**
     * 第三方系统登记注册到本系统
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/thethirdRegistration")
    @ResponseBody
    public String thethirdRegistration(Model model, HttpServletRequest request, HttpServletResponse response) {

        String registrationSecretKey = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_REGISTRATION_SECRET_KEY);
        String websiteName = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_WEBSITE_NAME);
        String homepage = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_HOMEPAGE);
        String callbackUrl = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_CALLBACK_URL);
        String callbackLogoutUrl = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_CALLBACK_LOGOUT_URL);

        Map<String, String> map = new HashMap<>();

        if (ThethirdConstant.REGISTRATION_SECRET_KEY.equals(registrationSecretKey)) {
            String sysId = DigestUtils.md5Hex(callbackUrl + callbackLogoutUrl + ThethirdConstant.MD5_SECRET_KEY);

            ThirdWebsiteInfo thirdWebsiteInfo = new ThirdWebsiteInfo();
            thirdWebsiteInfo.setWebsiteName(websiteName);
            thirdWebsiteInfo.setHomepage(homepage);
            thirdWebsiteInfo.setCallbackUrl(callbackUrl);
            thirdWebsiteInfo.setCallbackLogoutUrl(callbackLogoutUrl);

            SsSsoCacheData.thethirdSystemMap.put(sysId, thirdWebsiteInfo);

            map.put("code", "1");
            map.put("msg", "登记成功");
        } else {
            map.put("code", "0");
            map.put("msg", "权限错误");
        }

        String result = JSONObject.toJSONString(map);
        return result;
    }

    /**
     * Login
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response) {
        String registrationSecretKey = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_REGISTRATION_SECRET_KEY);
        String username = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_USERNAME);
        String password = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_PASSWORD);

        if (ThethirdConstant.REGISTRATION_SECRET_KEY.equals(registrationSecretKey)) {
            ReturnT<UserInfo> result = userService.findUser(username, password);
            if (result.getCode() != ReturnT.SUCCESS_CODE) {
                return new ReturnT<String>(result.getCode(), result.getMsg());
            }

            String userId = String.valueOf(result.getData().getUserid());

            XxlSsoUser xxlUser = SsoTokenLoginHelper.loginCheckByUserId(userId);

            String accessToken = "";
            if (xxlUser == null) {
                accessToken = SsoTokenLoginHelper.login(userId, username);
            } else {
                accessToken = xxlUser.getAccessToken();
                SsoTokenLoginHelper.updateAccessTokenUserIdMap(accessToken, userId);
            }

            return new ReturnT<String>(accessToken);
        }

        return new ReturnT<String>(ReturnT.FAIL_CODE, "权限错误");
    }

    /**
     * Logout
     *
     * @param sessionId
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response) {
        String registrationSecretKey = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_REGISTRATION_SECRET_KEY);
        String accessToken = request.getParameter(ThethirdConstant.SSO_ACCESS_TOKEN);

        if (ThethirdConstant.REGISTRATION_SECRET_KEY.equals(registrationSecretKey)) {
            SsoTokenLoginHelper.logout(accessToken);

            return ReturnT.SUCCESS;
        }

        return new ReturnT<String>(ReturnT.FAIL_CODE, "权限错误");
    }

    /**
     * logincheck
     *
     * @param sessionId
     * @return
     */
    @RequestMapping("/userinfo")
    @ResponseBody
    public ReturnT<XxlSsoUser> userinfo(HttpServletRequest request, HttpServletResponse response) {
        String registrationSecretKey = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_REGISTRATION_SECRET_KEY);
        String accessToken = request.getParameter(ThethirdConstant.SSO_ACCESS_TOKEN);

        if (ThethirdConstant.REGISTRATION_SECRET_KEY.equals(registrationSecretKey)) {
            XxlSsoUser xxlUser = SsoTokenLoginHelper.loginCheckByAccessToken(accessToken);

            if (xxlUser == null) {
                return new ReturnT<XxlSsoUser>(ReturnT.FAIL_CODE, "sso not login.");
            }

            return new ReturnT<XxlSsoUser>(xxlUser);
        }

        return new ReturnT<XxlSsoUser>(ReturnT.FAIL_CODE, "权限错误");
    }
}